
package roles;

import avenue.MyWindowEvent;
import avenue.Session;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.AppUser;
import model.DBManager;
import model.Module;
import model.RolePermission;
import model.UserRole;
import users.ListUsersForm;

/**
 *
 * @author Team-2
 */
public class ListRolesForm extends javax.swing.JFrame {


    /**
     * Creates new form ListUsersForm
     */
    public ListRolesForm() {
        em = DBManager.em;
        
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
        
        //Apply login user permissions
        addButton.setEnabled(Session.doesSessionUserHasPermissionType(
                                 Session.ROLES_MODULE, Session.CAN_CREATE));
        editButton.setEnabled(Session.doesSessionUserHasPermissionType(
                                 Session.ROLES_MODULE, Session.CAN_UPDATE));
        deleteButton.setEnabled(Session.doesSessionUserHasPermissionType(
                                 Session.ROLES_MODULE, Session.CAN_DELETE));          
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        roleQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select ur from  UserRole ur");
        roleList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(roleQuery.getResultList());
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        roleTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διαχείριση Ρόλων");
        setResizable(false);

        editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editButton.setText("Επεξεργασία");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteButton.setText("Διαγραφή");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        addButton.setText("Νέος");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        roleTable.setColumnSelectionAllowed(true);
        roleTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, roleList, roleTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleName}"));
        columnBinding.setColumnName("Όνομα Ρόλου");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(roleTable);
        roleTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jLabel1.setText("Ρόλοι");

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(deleteButton)
                        .addGap(18, 18, Short.MAX_VALUE)
                        .addComponent(editButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cancelButton)
                        .addGap(18, 18, 18)
                        .addComponent(saveButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addButton)
                    .addComponent(deleteButton)
                    .addComponent(editButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents
 
       
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
       
        ur = new UserRole();
        em.persist(ur);

        if (ur.getRolePermissionList() == null || 
            ur.getRolePermissionList().isEmpty()) {
            
            List<RolePermission> rolePermissionList = new ArrayList<RolePermission>();
            Query query = em.createQuery("select m from Module m");
            List<Module> moduleList = query.getResultList();
            for (Module module : moduleList) {
                RolePermission rp = new RolePermission();
                rp.setModuleId(module);
                rp.setRoleId(ur);
                em.persist(rp);
                rolePermissionList.add(rp);
            }
            ur.setRolePermissionList(rolePermissionList);
        }
        EditRoleForm erf = new EditRoleForm(ur, false);
        erf.setIconImage(Toolkit.getDefaultToolkit().getImage(Session.imgPath + "rolesIcon.png"));
        erf.setVisible(true);
        erf.setLocationRelativeTo(null); //center form
        thisFrame = this;
        thisFrame.setEnabled(false);
///////////////////////////Start Listeners//////////////////////////////////////
        erf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent) arg0).exitAndSave) {


                    roleList.add(ur);
                    int row = roleList.size() - 1;

                    roleTable.setRowSelectionInterval(row, row);
                    roleTable.scrollRectToVisible(roleTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                } else {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = roleQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    roleList.clear();
                    roleList.addAll(data);
                }
            }

            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_addButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed

        s=roleTable.getSelectedRow();
        if (s>=0) {   
          
           UserRole ur = roleList.get(roleTable.convertRowIndexToModel(s));
           try { //check if for this role exists related user    
                AppUser au = em.createNamedQuery("AppUser.findByRoleId",AppUser.class)
                               .setParameter("roleId", ur)
                               .getSingleResult(); 
                if (au==null) { //no related user                                 
                   roleList.remove(ur);
                   em.remove(ur);
                }else { 
                    String message = "Αδύνατη διαγραφή, ο ρόλος συσχετίζεται με χρήστη";
                    JOptionPane.showMessageDialog(this, message, "Προσοχή", 0);  
                }                  
           } catch (NoResultException ex) { //no related user
                roleList.remove(ur);
                em.remove(ur);    
           } catch (NonUniqueResultException ex) { //related woith more than one user
                    String message = "Αδύνατη διαγραφή, ο ρόλος συσχετίζεται με χρήστες";
                    JOptionPane.showMessageDialog(this, message, "Προσοχή", 0);                   
          }

        }
    }//GEN-LAST:event_deleteButtonActionPerformed
                                       
    
    
    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
    
    s=roleTable.getSelectedRow();
        
    if (s>=0) { // if has select a Role
        ur = roleList.get(roleTable.getSelectedRow());
        em.persist(ur);

        if( ur.getRolePermissionList() == null || ur.getRolePermissionList().isEmpty() ) {
            List<RolePermission> rolePermissionList = new ArrayList<RolePermission>();
            Query query = em.createQuery("select m from Module m");
            List<Module> modules = query.getResultList();
            for (Module module : modules) {
                RolePermission rp = new RolePermission();
                rp.setModuleId(module);
                rp.setRoleId(ur);
                em.persist(rp);
                rolePermissionList.add(rp);
            }
            ur.setRolePermissionList(rolePermissionList);
        }

        EditRoleForm erf = new EditRoleForm(ur,false);
        erf.setIconImage(Toolkit.getDefaultToolkit().getImage(Session.imgPath + "rolesIcon.png"));
        erf.setVisible(true);
        erf.setLocationRelativeTo(null); //center form
        thisFrame=this;
        thisFrame.setEnabled(false);
               
///////////////////////////Start Listeners//////////////////////////////////////            
        erf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){                                        
                    roleTable.setRowSelectionInterval(s, s);
                    roleTable.scrollRectToVisible(roleTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = roleQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    roleList.clear();
                    roleList.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        }  
    }//GEN-LAST:event_editButtonActionPerformed

    
    
    
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
      
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
         em.getTransaction().rollback();
       this.setVisible(false); 
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        
        em.getTransaction().commit();
        em.getTransaction().begin();
         dispose();

    }//GEN-LAST:event_saveButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListRolesForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<UserRole> roleList;
    private javax.persistence.Query roleQuery;
    private javax.swing.JTable roleTable;
    private javax.swing.JButton saveButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    UserRole ur;
    EntityManager em;
    JFrame thisFrame;
    int s;
}
